package egovframework.npqs.pqi.mobile.activity;

import java.util.HashMap;

import com.sds.BizAppLauncher.gov.aidl.GovController;
import com.sds.BizAppLauncher.gov.aidl.GovController.IGovCallback;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsonparser.CompanySearchThread;
import egovframework.npqs.pqi.mobile.jsonparser.ProdResultThread;
import egovframework.npqs.pqi.mobile.jsonparser.ProdResultThread.ProdResultThreadCallback;
import egovframework.npqs.pqi.mobile.util.BrUtilManager;

//품목결과검색
public class ProdSearchActivity extends Activity implements OnClickListener
	, ProdResultThreadCallback{
	private TextView titleTxt, navigation;
	//private TextView textCnt;  //검색검수
	private AppStatus myapp;
	private Context context;
	private ListView listView;
	
	//private ImageButton searchBtn;
	private ImageButton prodSearchBtn, btnHome, btn_exit;
	
	private ProdResultThread prodThread;
	private ProdResultListAdapter prodListAdapter;
	
	private Button footerBtn01, footerBtn02, footerBtn03, footerBtn04;	// 하단 버튼
	private ImageButton searchDateBtn03, searchDateBtn05, searchDateBtn06, clear_btn;	// 3개월전, 5개월전, 6개월전 버튼
	
	private EditText prodCdEdit;
	//private EditText prodNameEdit;
	
	private EditText sdateEdit, edateEdit;
	private ImageButton sCalenderBtn, eCalenderBtn;
	
	private int nTotCnt = 0;	// 리스트 카운트 수
	
	private String korNm, prdCode, code;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    
    HashMap<String,String> searchMap;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("품목결과검색");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_prod_search);

		init();
		
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) context.getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("품목결과검색");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		korNm="";
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		prodCdEdit = (EditText)findViewById(R.id.edit_prod_cd);  //품목코드Edit
		prodSearchBtn = (ImageButton)findViewById(R.id.btn_prod_search);  //검색버튼
		prodSearchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchProd();
			}
		});
		
		clear_btn = (ImageButton)findViewById(R.id.clear_btn); //글자 초기화 버튼
		clear_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				prodCdEdit.setText("");
			}
		});
		/*prodNameEdit = (EditText)findViewById(R.id.edit_prod_name); //품목명Edit
		searchBtn = (ImageButton)findViewById(R.id.search_btn);  //조회버튼
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchProdResult();
			}
		});*/

		listView = (ListView)findViewById(R.id.quarantine_list);
		prodListAdapter = new ProdResultListAdapter();
		
		//textCnt = (TextView)findViewById(R.id.text_cnt);
		
		sdateEdit = (EditText)findViewById(R.id.edit_sdate);	// 시작일자 에디트 박스
		edateEdit = (EditText)findViewById(R.id.edit_edate);	// 종료일자 에디트 박스
		
		sdateEdit.setText(BrUtilManager.getMonthAgoDate(3));
		edateEdit.setText(BrUtilManager.getCurrentDateTime(0));
		
		sCalenderBtn = (ImageButton)findViewById(R.id.btn_s_calender);
		eCalenderBtn = (ImageButton)findViewById(R.id.btn_e_calender);
		
		sCalenderBtn.setOnClickListener(this);
		eCalenderBtn.setOnClickListener(this);
		
		sdateEdit.setInputType(InputType.TYPE_NULL);
		edateEdit.setInputType(InputType.TYPE_NULL);
		
		footerBtn01 = (Button)findViewById(R.id.footer01Btn);
		footerBtn02 = (Button)findViewById(R.id.footer02Btn);
		footerBtn03 = (Button)findViewById(R.id.footer03Btn);
		footerBtn04 = (Button)findViewById(R.id.footer04Btn);
		
		searchDateBtn03 = (ImageButton)findViewById(R.id.btn_three_month);
		searchDateBtn05 = (ImageButton)findViewById(R.id.btn_five_month);
		searchDateBtn06 = (ImageButton)findViewById(R.id.btn_six_month);
		
		searchDateBtn03.setBackgroundResource(R.drawable.btn_three_month_on);
		
		footerBtn01.setOnClickListener(this);
		footerBtn02.setOnClickListener(this);
		footerBtn03.setOnClickListener(this);
		footerBtn04.setOnClickListener(this);
		
		searchDateBtn03.setOnClickListener(this);
		searchDateBtn05.setOnClickListener(this);
		searchDateBtn06.setOnClickListener(this);
		
	}
	
	private void searchProdResult(){
		/*if(prodCdEdit.getText().toString().equals("")){ //&&prodNameEdit.getText().toString().equals("")
			myapp.utilm.ShowDialog(ProdSearchActivity.this, "실패", "품목코드 or 품목명을 먼저 조회해주세요.", 20);
			return;
		}*/
		searchList();
	}
	
	private void searchList(){	// 검역신청번호로 조회 (상세조회아님)
		searchMap = new HashMap<String,String>();
		//code = "";
		/*if(!prodCdEdit.getText().toString().equals("")){
			code = prodCdEdit.getText().toString();
		}else{
			code = prodCdEdit.getText().toString();
		}*/
		searchMap.put("sDate", sdateEdit.getText().toString());
		searchMap.put("eDate", edateEdit.getText().toString());
		searchMap.put("code", code);
		
		myapp.utilm.InputKeybordHidden(context, prodCdEdit);
		
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "검색";
		threadStart();
		//searchClear();
	}
	
	/*private void searchList(){	// 검역신청번호로 조회 (상세조회아님)
		showDialogNo();
		HashMap<String,String>	searchMap = new HashMap<String,String>();
		String code = "";
		
		if(!prodNameEdit.getText().toString().equals("") && !prodCdEdit.getText().toString().equals("")){
			code = prodCdEdit.getText().toString();
		}else{
			if(!prodNameEdit.getText().toString().equals("")){
				code = prodNameEdit.getText().toString();
			}else{
				code = prodCdEdit.getText().toString();
			}
		}
		
		searchMap.put("sDate", sdateEdit.getText().toString());
		searchMap.put("eDate", edateEdit.getText().toString());
		searchMap.put("code", code);
		
		
		prodThread = new ProdResultThread(context, this, searchMap);
		prodThread.start();
		
		myapp.utilm.InputKeybordHidden(context, prodNameEdit);
		myapp.utilm.InputKeybordHidden(context, prodCdEdit);
		//searchClear();
	}*/
	
	private void searchProd(){
		String prodCd;
		if(prodCdEdit.getText().toString().equals("")){
			myapp.utilm.ShowDialog(ProdSearchActivity.this, "실패", "품목코드 or 품목명을 1 글자 이상 입력해주세요.", 20);
			return;
		}else{
			Intent intent = new Intent(ProdSearchActivity.this, ProdDetailActivity.class);
			if(!prodCdEdit.getText().toString().equals("")){
				prodCd = prodCdEdit.getText().toString();
			}else{
				prodCd = prodCdEdit.getText().toString();
			}
			intent.putExtra("prodCd", prodCd);
			startActivityForResult(intent, 1);	
		}
	}
	/*private void searchProd(){
		String prodCd;
		if(prodCdEdit.getText().toString().equals("") && prodNameEdit.getText().toString().equals("")){
			myapp.utilm.ShowDialog(ProdSearchActivity.this, "실패", "품목코드 or 품목명을 입력해주세요.", 20);
			return;
		}else{
			Intent intent = new Intent(ProdSearchActivity.this, ProdDetailActivity.class);
			
			if(!prodNameEdit.getText().toString().equals("") && !prodCdEdit.getText().toString().equals("")){
				prodCd = prodCdEdit.getText().toString();
			}else{
				if(!prodNameEdit.getText().toString().equals("")){
					prodCd = prodNameEdit.getText().toString();
				}else{
					prodCd = prodCdEdit.getText().toString();
				}
			}
			intent.putExtra("prodCd", prodCd);
			startActivityForResult(intent, 1);	
		}
	}*/
	
	public void threadStart(){
		if("검색".equals(temp)){
    		prodThread = new ProdResultThread(context, this, searchMap, AppStatus.getmUserId());
    		prodThread.start();
    	}
	}
	
	private void searchClear(){
		sdateEdit.setText(BrUtilManager.getMonthAgoDate(3));
		edateEdit.setText(BrUtilManager.getCurrentDateTime(0));
			
		searchDateBtn03.setBackgroundResource(R.drawable.btn_three_month_on);
		searchDateBtn05.setBackgroundResource(R.drawable.btn_five_month_off);
		searchDateBtn06.setBackgroundResource(R.drawable.btn_six_month_off);
	}
	
	@Override
	public void OnProdResultCompleted(boolean isNetworkConntected,
			boolean results, String message) {
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(results) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void OnProdResultError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				
				nTotCnt = myapp.getArrProdResultItem().size();
				//textCnt.setText("총 "+nTotCnt+"건이 조회되었습니다.");
				prodListAdapter.notifyDataSetChanged();
				listView.setAdapter(prodListAdapter);	
				
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				//textCnt.setText("데이터가 존재하지 않습니다.");
				prodListAdapter.notifyDataSetChanged();
				listView.setAdapter(prodListAdapter);
				myapp.utilm.ShowDialog(ProdSearchActivity.this, "실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(ProdSearchActivity.this, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	class ProdResultListAdapter extends BaseAdapter {
		TextView prod_inst_name, prod_dsps_name, prod_rec_no, prod_fie_date, prod_prod_name, prod_nat_name;

		@Override
		public int getCount() {
			return myapp.getArrProdResultItem().size();
		}

		@Override
		public Object getItem(int position) {
			return myapp.getArrProdResultItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			//if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_prod_item, parent, false);
    		//}
			
			prod_inst_name = (TextView)convertView.findViewById(R.id.prod_inst_name);
			prod_dsps_name = (TextView)convertView.findViewById(R.id.prod_dsps_name);
			prod_rec_no = (TextView)convertView.findViewById(R.id.prod_rec_no);
			prod_fie_date = (TextView)convertView.findViewById(R.id.prod_fie_date);
			prod_prod_name = (TextView)convertView.findViewById(R.id.prod_prod_name);
			prod_nat_name = (TextView)convertView.findViewById(R.id.prod_nat_name);
			
			prod_inst_name.setText(myapp.getArrProdResultItem().get(position).getAllInsttNm());
			prod_dsps_name.setText(myapp.getArrProdResultItem().get(position).getDspsTrgetNm());
			prod_rec_no.setText(myapp.getArrProdResultItem().get(position).getFullRecNo());
			prod_fie_date.setText(myapp.getArrProdResultItem().get(position).getFieDe());
			prod_prod_name.setText(myapp.getArrProdResultItem().get(position).getPrdlstNm());
			prod_nat_name.setText(myapp.getArrProdResultItem().get(position).getNatNm());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			Intent intent = new Intent(ProdSearchActivity.this , ProdDetailStatusActivity.class);
			intent.putExtra("resOffCd", myapp.getArrProdResultItem().get(position).getResOffCd());
			intent.putExtra("resNo", myapp.getArrProdResultItem().get(position).getResNo());
			intent.putExtra("resSeq", myapp.getArrProdResultItem().get(position).getResSeq());
			startActivity(intent);
		}
	}
	
	private void sDateSetting(){
		String str = sdateEdit.getText().toString();
		int sYear, sDay, sMonth;
		
		sYear = Integer.parseInt(str.substring(0, 4));
		sMonth = Integer.parseInt(str.substring(5, 7)) -1;
		sDay = Integer.parseInt(str.substring(8, 10));
		
		DatePickerDialog dpd = new DatePickerDialog(ProdSearchActivity.this,
		        new DatePickerDialog.OnDateSetListener() {
		 
		            @Override
		            public void onDateSet(DatePicker view, int year,
		                    int monthOfYear, int dayOfMonth) {
		            	String months = "";
		            	String days = "";
		            	if(String.valueOf(monthOfYear + 1).length() == 1){
		            		months ="0"+(monthOfYear+1);
		            	}else{
		            		months = String.valueOf((monthOfYear+1));
		            	}
		            	
		            	if(String.valueOf(dayOfMonth).length() == 1){
		            		days ="0"+dayOfMonth;
		            	}else{
		            		days =String.valueOf(dayOfMonth);		            		
		            	}
		            	
		                sdateEdit.setText(year + "-" + months + "-" + days);
		 
		            }
		        }, sYear, sMonth, sDay);
		dpd.show();
		
	}
	
	private void eDateSetting(){
		String str = edateEdit.getText().toString();
		int eYear, eDay, eMonth;
		
		eYear = Integer.parseInt(str.substring(0, 4));
		eMonth = Integer.parseInt(str.substring(5, 7)) -1;
		eDay = Integer.parseInt(str.substring(8, 10));
		
		DatePickerDialog dpd = new DatePickerDialog(ProdSearchActivity.this,
		        new DatePickerDialog.OnDateSetListener() {
		 
		            @Override
		            public void onDateSet(DatePicker view, int year,
		                    int monthOfYear, int dayOfMonth) {
		            	String months = "";
		            	String days = "";
		            	
		            	if(String.valueOf(monthOfYear + 1).length() == 1){
		            		months ="0"+(monthOfYear+1);
		            	}else{
		            		months = String.valueOf((monthOfYear+1));
		            	}
		            	
		            	if(String.valueOf(dayOfMonth).length() == 1){
		            		days ="0"+dayOfMonth;
		            	}else{
		            		days =String.valueOf(dayOfMonth);		            		
		            	}
		            	
		                edateEdit.setText(year + "-" + months + "-" + days);
		            }
		        }, eYear, eMonth, eDay);
		dpd.show();
		
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		/*case R.id.footer01Btn:
			break;
		case R.id.footer02Btn:	// 품목결과검색 화면 새창으로 띄움
			Intent intent = new Intent(context, ProdSearchActivity.class);
			startActivity(intent);
			break;
		case R.id.footer03Btn:	// 검역대기 조회 화면으로 화면 전환
			QuarantineResultList incomeResultList = new QuarantineResultList();
			addFragmentReplace(R.id.base_frame, incomeResultList, QuarantineResultList.class.getName());
			break;
		case R.id.footer04Btn:	// 소독대기 조회 화면으로 화면 전환
			DisinfectionResultList disinfectionResultList = new DisinfectionResultList();
			addFragmentReplace(R.id.base_frame, disinfectionResultList, DisinfectionResultList.class.getName());			
			break;	*/	
		case R.id.btn_three_month:
				searchDateBtn03.setBackgroundResource(R.drawable.btn_three_month_on);
				searchDateBtn05.setBackgroundResource(R.drawable.btn_five_month_off);
				searchDateBtn06.setBackgroundResource(R.drawable.btn_six_month_off);
				sdateEdit.setText(BrUtilManager.getMonthAgoDate(3));
				edateEdit.setText(BrUtilManager.getCurrentDateTime(0));
				
			break;
		case R.id.btn_five_month:
				searchDateBtn03.setBackgroundResource(R.drawable.btn_three_month_off);
				searchDateBtn05.setBackgroundResource(R.drawable.btn_five_month_on);
				searchDateBtn06.setBackgroundResource(R.drawable.btn_six_month_off);
				sdateEdit.setText(BrUtilManager.getMonthAgoDate(5));
				edateEdit.setText(BrUtilManager.getCurrentDateTime(0));				
			break;
		case R.id.btn_six_month:
				searchDateBtn03.setBackgroundResource(R.drawable.btn_three_month_off);
				searchDateBtn05.setBackgroundResource(R.drawable.btn_five_month_off);
				searchDateBtn06.setBackgroundResource(R.drawable.btn_six_month_on);
				sdateEdit.setText(BrUtilManager.getMonthAgoDate(6));
				edateEdit.setText(BrUtilManager.getCurrentDateTime(0));				
			break;
		case R.id.btn_s_calender:
				sDateSetting();
				
			break;

		case R.id.btn_e_calender:
				eDateSetting();
			
		break;			
			
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if(resultCode == 1){
				prdCode = BrUtilManager.isNullCheck2(data.getStringExtra("prdlstCode"));
				korNm = BrUtilManager.isNullCheck2(data.getStringExtra("korNm"));
				Log.i("prdCode", prdCode);
				code = prdCode;
				Log.i("code", code);
				//prodCdEdit.setText(data.getStringExtra("prdCode"));
				//prodNameEdit.setText(data.getStringExtra("korNm"));	
				searchProdResult();
			}else{
			}
			break;

		default:
			break;
		}
	}
	
	@Override
	protected void onResume() {
		if(myapp.isAbleHome()){
			finish();
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
	
}
